package com.plian.system.service.lg.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.lg.MlegalProceedingsArbitrationDTO;
import com.plian.system.entity.lg.MlegalProceedingsArbitration;
import com.plian.system.mapper.lg.MlegalProceedingsArbitrationMapper;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.service.lg.IMlegalProceedingsArbitrationService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.lg.MlegalProceedingsArbitrationVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.lg.MlegalProceedingsArbitrationWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 服务实现类
 *
 * @author gangan
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class MlegalProceedingsArbitrationServiceImpl extends BaseServiceImpl<MlegalProceedingsArbitrationMapper, MlegalProceedingsArbitration> implements IMlegalProceedingsArbitrationService, BaseFlowService {

	private FormWorkflowService formWorkflowService;

	private OrgzationService orgzationService;

	private IFormCodeService formCodeService;

	private FileService fileService;

	private MlegalProceedingsArbitrationWrapper mlegalProceedingsArbitrationWrapper;

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean saveOrUpdate(MlegalProceedingsArbitration mlegalProceedingsArbitration) {

		if (!Optional.ofNullable(mlegalProceedingsArbitration.getStatus()).isPresent()) {
			mlegalProceedingsArbitration.setStatus(FormStatusConstant.UNREVIEWED);
		}
		boolean flag = false;
		if (!Optional.ofNullable(mlegalProceedingsArbitration.getId()).isPresent()) {
			flag = true;
			mlegalProceedingsArbitration.setCode(formCodeService.getCode(FormTypeConstant.LG_PROCEEDINGS_ARBITRATION_FORM));
			mlegalProceedingsArbitration.setFormType(String.valueOf(FormTypeConstant.LG_PROCEEDINGS_ARBITRATION_FORM));
			mlegalProceedingsArbitration.setVersion("1.0");
		}
		boolean result = super.saveOrUpdate(mlegalProceedingsArbitration);
		if (flag){
			fileService.saveAll(String.valueOf(mlegalProceedingsArbitration.getId()), mlegalProceedingsArbitration.getDocList());
		}else {
			fileService.edit(String.valueOf(mlegalProceedingsArbitration.getId()), mlegalProceedingsArbitration.getDocList());
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			MlegalProceedingsArbitration mlegalProceedingsArbitration = getById(id);
			if (mlegalProceedingsArbitration == null) {
				return false;
			} else if (mlegalProceedingsArbitration.getStatus() != null &&
					(mlegalProceedingsArbitration.getStatus() != FormStatusConstant.STASH && mlegalProceedingsArbitration.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}
		return super.deleteLogic(ids);
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}

	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus  更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			MlegalProceedingsArbitration mlegalProceedingsArbitration = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				mlegalProceedingsArbitration.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				mlegalProceedingsArbitration.setApprovedTime(now);
			}
			mlegalProceedingsArbitration.setStatus(updateStatus);
			updateById(mlegalProceedingsArbitration);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}

	@Override
	public Boolean checkIsExisted(Long id, String code) {
		boolean result = true;
		if (Optional.ofNullable(code).isPresent()) {
			MlegalProceedingsArbitration mlegalProceedingsArbitration = new MlegalProceedingsArbitration();
			mlegalProceedingsArbitration.setCode(code);
			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(mlegalProceedingsArbitration))).isPresent()) {
				if (id == null || !id.equals(getOne(Condition.getQueryWrapper(mlegalProceedingsArbitration)).getId())) {
					result = false;
				}
			}
		}
		return result;
	}

	@Override
	public ReportReturnVO legalArbitrationSurvey(MlegalProceedingsArbitrationDTO mlegalProceedingsArbitrationDTO) {
		List<String> longList = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(mlegalProceedingsArbitrationDTO.getFillingUnitIds())){
			try {
				for (String unitId : mlegalProceedingsArbitrationDTO.getFillingUnitIds()){
					List<PageData> orgs = orgzationService.getChlidList(unitId);
					longList.add(unitId);
					if (CollectionUtil.isNotEmpty(orgs)){
						for (PageData p : orgs){
							longList.add((String)p.get("id"));
						}
					}
				}
			}catch (Exception e){
				log.error(ExceptionUtils.getFullStackTrace(e));
			}
		}

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		ReportVO reportVO = new ReportVO();
		reportVO
			.addHeader(HeaderVO.builder().key("fillingUnitName").title("单位").build())
			.addHeader(HeaderVO.builder().key("occurrenceTime").title("发生时间").build())
			.addHeader(HeaderVO.builder().key("parties").title("当事人各方").build())
			.addHeader(HeaderVO.builder().key("amountInvolved").title("涉案金额（万元）").build())
			.addHeader(HeaderVO.builder().key("caseFocus").title("案情焦点及争议").build())
			.addHeader(HeaderVO.builder().key("processingMeasuresResults").title("处理措施和结果（未结案件填结果预测）").build())
			.addHeader(HeaderVO.builder().key("processingProgress").title("处理进度").build())
			.addHeader(HeaderVO.builder().key("remark").title("备注").build());

		List<MlegalProceedingsArbitrationVO> mlegalProceedingsArbitrationVOList = baseMapper.legalArbitrationSurvey(mlegalProceedingsArbitrationDTO.getStartTime(),
				mlegalProceedingsArbitrationDTO.getEndTime(), longList, mlegalProceedingsArbitrationDTO.getParties(),
				mlegalProceedingsArbitrationDTO.getAmountInvolved());
		reportVO.setData(mlegalProceedingsArbitrationVOList);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}



	@Override
	public File buildpdf(String fillingUnitId, String startTime, String endTime) {
		try{
			int length = 0 ;
			PageData pd = new PageData();
			pd.put("id", fillingUnitId);
			PageData unit = orgzationService.findbyid(pd).getPageData();

			List<String> longList = new ArrayList<>();
			List<PageData> orgs = orgzationService.getChlidList(fillingUnitId);
			String[] split = fillingUnitId.split(",");
			if (CollectionUtil.isNotEmpty(orgs)){
				for (PageData p : orgs){
					longList.add((String)p.get("id"));
				}
			}else {
				Collections.addAll(longList, split);
			}
			Date startDate = null;
			if (StringUtil.isNotBlank(startTime)){
				startDate = DateUtil.parse(startTime, DateUtil.PATTERN_DATE);
			}
			Date endDate = null;
			if (StringUtil.isNotBlank(endTime)){
				endDate = DateUtil.parse(endTime, DateUtil.PATTERN_DATE);
			}

			List<MlegalProceedingsArbitrationVO> list = baseMapper.legalArbitrationSurvey(startDate, endDate, longList, null, null);
			length = list.size();
			String[][] info =new String[length][9];
			for(int i=0;i<length;i++){
				info[i][0] = String.valueOf(i+1);
				info[i][1] = list.get(i).getFillingUnitName();
				if(Optional.ofNullable(list.get(i).getCreateTime()).isPresent()){
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
					info[i][2] = simpleDateFormat.format(list.get(i).getCreateTime());
				}else{
					info[i][2] = "";
				}
				info[i][3] = list.get(i).getParties();
				if(Optional.ofNullable(list.get(i).getAmountInvolved()).isPresent()){
					info[i][4] = list.get(i).getAmountInvolved().toString();
				}else{
					info[i][4] = "";
				}
				info[i][5] = list.get(i).getCaseFocus();
				info[i][6] = list.get(i).getProcessingMeasuresResults();
				info[i][7] = list.get(i).getProcessingProgress();
				info[i][8] = list.get(i).getRemark();
			}


			Document document = new Document(com.itextpdf.text.PageSize.A4, 90, 83, 30, 40);
			FileOutputStream fs;
			BaseFont bfHeiTi;
			BaseFont bfST;
			BaseFont test;
			BaseFont bfbt;
			String substring = fillingUnitId.substring(0, 32);

			File pdffile = File.createTempFile(substring, ".pdf");
			if (pdffile.exists()) {
				pdffile.delete();
			}

			fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
			PdfWriter.getInstance(document, fs);

			// 打开文档
			document.open();
			bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

			// 创建了一页
			Font font_Zhengwen = new Font(bfST, 10.0f, Font.NORMAL, BaseColor.BLACK);
			// 添加标题
			Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
			Font font_biaotou1 = new Font(test, 12.0f, Font.NORMAL, BaseColor.BLACK);
			Font font_biaotou2 = new Font(bfbt, 11.0f, Font.NORMAL, BaseColor.BLACK);

			// 创建一个段落
			String title = "市属企业重大法律诉讼及仲裁案件情况调查表";
			Paragraph biaoti = new Paragraph(title, font_Biaoti);
			biaoti.setAlignment(1);
			biaoti.setSpacingAfter(20f);
			document.add(biaoti);

			// 设置表格的列宽
			float[] widths = { 30f, 60f, 45f, 40f, 35f, 40f ,50f, 40f, 35f};
			// 建立一个pdf表格
			PdfPTable table = new PdfPTable(widths);
			// 设置表格上面空白宽度
			table.setSpacingBefore(10f);
			// 设置表格下面空白宽度
			table.setSpacingAfter(0f);
			// 设置表格的宽度
			table.setTotalWidth(520);
			PdfPCell cell = new PdfPCell();
			PdfPCell cell2 = new PdfPCell();
			cell.setMinimumHeight(25f);
			cell2.setMinimumHeight(25f);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

			PdfPCell cell3 = new PdfPCell();
			PdfPCell cell4 = new PdfPCell();
			PdfPCell cell5 = new PdfPCell();
			PdfPCell cell6 = new PdfPCell();
			cell3.setMinimumHeight(25f);
			cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell4.setMinimumHeight(25f);
			cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell5.setMinimumHeight(25f);
			cell5.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell6.setMinimumHeight(25f);
			cell6.setVerticalAlignment(Element.ALIGN_MIDDLE);
			table.setLockedWidth(true);

			//正式开始
			if (Optional.ofNullable(unit).isPresent()){
				cell3.setPhrase(new Paragraph("填报单位（盖章）："+unit.get("name"),font_Zhengwen));
				cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
				cell3.disableBorderSide(13);
				cell3.setColspan(9);
				table.addCell(cell3);
			}else {
				cell3.setPhrase(new Paragraph("填报单位（盖章）：",font_Zhengwen));
				cell3.setHorizontalAlignment(Element.ALIGN_LEFT);
				cell3.disableBorderSide(13);
				cell3.setColspan(9);
				table.addCell(cell3);
			}

			cell.setPhrase(new Paragraph("序号", font_biaotou2));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setColspan(1);
			table.addCell(cell);

			cell.setPhrase(new Paragraph("单位", font_biaotou2));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);

			cell.setPhrase(new Paragraph("发生时间", font_biaotou2));
			table.addCell(cell);

			cell.setPhrase(new Paragraph("当事人各方", font_biaotou2));
			table.addCell(cell);

			cell.setPhrase(new Paragraph("涉案\n金额\n(万元)", font_biaotou2));
			table.addCell(cell);

			cell.setPhrase(new Paragraph("案情焦点及争议", font_biaotou2));
			table.addCell(cell);

			cell.setPhrase(new Paragraph("处理措施和结果(未结案件填结果预测)", font_biaotou2));
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setPaddingTop(5);
			cell.setPaddingBottom(5);
			table.addCell(cell);

			cell.setPhrase(new Paragraph("处理进度", font_biaotou2));
			table.addCell(cell);

			cell.setPhrase(new Paragraph("备注", font_biaotou2));
			table.addCell(cell);

			length = info.length<8?8:info.length;
			for(int i=0;i<length;i++){
				for(int j=0;j<9;j++){
					if(i<info.length){
						cell2.setPhrase(new Paragraph(info[i][j],font_Zhengwen));
					}else{
						cell2.setPhrase(new Paragraph("",font_Zhengwen));
					}
					cell2.setColspan(1);
					cell2.setRowspan(1);
					cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
					cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
					cell2.setPaddingTop(5);
					cell2.setPaddingBottom(5);
					table.addCell(cell2);
				}
			}

			String remark = "注：1.本表所指重大案件是指涉案金额在500万元以上的案件；\n" +
				"    2.“填报单位”填写集团公司名称，表格中“单位”填写集团公司下属分（子）公司。";
			cell.setPhrase(new Paragraph(remark, font_biaotou2));
			cell.setColspan(9);
			cell.setHorizontalAlignment(Element.ALIGN_LEFT);
			table.addCell(cell);

			cell4.setPhrase(new Paragraph("填报人：",font_Zhengwen));
			cell4.setHorizontalAlignment(Element.ALIGN_LEFT);
			cell4.disableBorderSide(14);
			cell4.setColspan(3);
			table.addCell(cell4);

			cell5.setPhrase(new Paragraph("联系电话：",font_Zhengwen));
			cell5.disableBorderSide(14);
			cell5.setColspan(3);
			table.addCell(cell5);

			cell6.setPhrase(new Paragraph("填报时间：        年        月",font_Zhengwen));
			cell6.setHorizontalAlignment(Element.ALIGN_RIGHT);
			cell6.disableBorderSide(14);
			cell6.setColspan(3);
			table.addCell(cell6);

			document.add(table);
			document.close();
			return pdffile;
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}

		return null;
	}

	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<MlegalProceedingsArbitration> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(MlegalProceedingsArbitration::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<MlegalProceedingsArbitration> mlegalProceedingsArbitrations = list(queryWrapper);
		List<MlegalProceedingsArbitrationVO> mlegalProceedingsArbitrationsVOS= mlegalProceedingsArbitrationWrapper.entityToVO(mlegalProceedingsArbitrations);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(mlegalProceedingsArbitrationsVOS)){
				for (MlegalProceedingsArbitrationVO vo : mlegalProceedingsArbitrationsVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getFillingUnitName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFillingUnitId());
					pd.put("formType", FormTypeConstant.LG_PROCEEDINGS_ARBITRATION_FORM);
					pd.put("orgName", vo.getFillingUnitName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Collections.singletonList(FormTypeConstant.LG_PROCEEDINGS_ARBITRATION_FORM);
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED);
	}
}
